import React, { useEffect, useState } from 'react';
import { Container, Input, InputGroup } from 'rsuite';
import SearchIcon from '@rsuite/icons/Search';
import Api from './Api';
import { ModelViewer as ModelViewer } from './ModelViewer';


var viewer: ModelViewer;

function animate(dt: number) {
  if (viewer) {
    viewer.render(dt);
  }
  requestAnimationFrame(animate);
}


export default function App() {
  const [inited] = useState<Array<number>>([]);
  const [updator, setUpdator] = useState(0);
  const [keyword, setKeyword] = useState('');
  let canvasRef = React.createRef<HTMLCanvasElement>();

  useEffect(() => {
    if (canvasRef.current instanceof HTMLCanvasElement) {
      let canvas = canvasRef.current;
      if (inited.length == 0) {
        inited.push(Date.now());
        viewer = new ModelViewer(canvas);
        animate(0);
      } else {
        if (viewer) {
          viewer.resize();
        }
      }


      if (viewer) {
        viewer.barControls.onSelect = (obj: THREE.Object3D) => {
          let key = obj.userData.tags || '';
          console.log('key', key);
          setKeyword(key);
          setUpdator(updator + 1);
        }
      }
    }
  }, [updator]);

  const search = async () => {
    const rows = await Api.search(keyword, 0, 10);
    if (viewer) {
      viewer.setRows(rows)
    }
  }

  return (
    <Container>
      <canvas ref={canvasRef}></canvas>
      <InputGroup style={{ position: 'absolute', bottom: 40, left: "8%", width: '84%' }}>
        <Input onPressEnter={search} value={keyword} onChange={(v) => setKeyword(v)}></Input>
        <InputGroup.Button>
          <SearchIcon onClick={search} />
        </InputGroup.Button>
      </InputGroup>
    </Container>
  )
}

